package com.ycshihuo.shihuo.shiroConfig;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ShihuoRealm extends AuthorizingRealm {

    Map<String, String> map = new HashedMap();
    {
        map.put("admin", "a66abb5684c45962d887564f08346e8d");
        super.setName("shihuoRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        Set roles = getRolesByusername(username);
        Set permissions = getPermissionsByname();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);

        return simpleAuthorizationInfo;
    }

    private Set getPermissionsByname() {
        Set set = new HashSet();
        set.add("admin:add");
        set.add("admin:delete");
        return set;
    }

    private Set getRolesByusername(String username) {
        Set set = new HashSet();
        set.add("admin");
        set.add("user");
        return set;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //1从主体传过来的认证信息中获取username
        String username = (String) authenticationToken.getPrincipal();

        //2通过用户名获取凭证
        String password = getPasswordByName(username);
        if (null == password) {
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("admin", "a66abb5684c45962d887564f08346e8d", "shihuoRealm");
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("admin"));
        return simpleAuthenticationInfo;
    }

    //模拟从数据库中获取数据
    private String getPasswordByName(String username) {
        return map.get(username);
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456", "admin");
        System.out.println(md5Hash.toString());
    }
}
